package com.zhuguowei.chapter_2_4.aidl;

import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.os.SystemClock;
import android.util.Log;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

public class BookManagerService extends Service {

    private static final String TAG = "BookManagerService";
    private CopyOnWriteArrayList<Book> mBookList = new CopyOnWriteArrayList<Book>();
    // zgw-2017/12/1 16:34
    private AtomicBoolean mIsServiceDestoryed = new AtomicBoolean(false);
    /* 屏蔽CopyOnWriteArrayList，改用RemoteCallbackList @modify by zhuguowei 2017/12/4 15:09 */
//    private CopyOnWriteArrayList<IOnNewBookArrivedListener> mListeners = new CopyOnWriteArrayList<>();
    private RemoteCallbackList<IOnNewBookArrivedListener> mListeners = new RemoteCallbackList<>();

    public BookManagerService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mBookList.add(new Book(1, "Android"));
        mBookList.add(new Book(2, "IOS"));
        //[开启线程，异步进行通知新书到达的工作] zgw-2017/12/1 16:55
        new Thread(new ServiceWorker()).start();
    }


    private Binder mBinder = new IBookManager.Stub() {

        @Override
        public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
            int check = checkCallingOrSelfPermission("com.zhuguowei.chapter_2_4.ACCESS_BOOK_SERVICE");
            Log.e(TAG, "onTransact: chenk = " + check);
            if (check == PackageManager.PERMISSION_DENIED) {
                Log.e(TAG, "onTransact: 1--未申请权限！！！");
                return false;
            }

            String packageName = null;
            String[] packages = getPackageManager().getPackagesForUid(getCallingUid());
            if (packages != null && packages.length > 0) {
                packageName = packages[0];
            }
            if (!packageName.startsWith("com.zhuguowei")) {
                Log.e(TAG, "onTransact: 2--未申请权限！！！");
                return false;
            }
            Log.e(TAG, "onTransact: 已获得权限！！！");
            return super.onTransact(code, data, reply, flags);
        }

        @Override
        public List<Book> getBookList() throws RemoteException {
            SystemClock.sleep(5000);
            return mBookList;
        }

        @Override
        public void addBook(Book book) throws RemoteException {
            mBookList.add(book);
        }

        //注册 zgw-2017/12/1 16:51
        @Override
        public void registerListener(IOnNewBookArrivedListener listener) throws RemoteException {
            /* 屏蔽CopyOnWriteArrayList，改用RemoteCallbackList @modify by zhuguowei 2017/12/4 15:09
            if (!mListeners.contains(listener)) {
                mListeners.add(listener);
            } else {
                Log.e(TAG, "registerListener: already exists !");
            }
            Log.e(TAG, "register listener：" + listener);
            Log.e(TAG, "registerListener: mListeners size = " + mListeners.size());
            屏蔽CopyOnWriteArrayList，改用RemoteCallbackList @modify by zhuguowei 2017/12/4 15:09 */
            //RemoteCallbackList zgw-2017/12/4 15:25
            mListeners.register(listener);
            final int N = mListeners.beginBroadcast();
            mListeners.finishBroadcast();
            Log.e(TAG, "registerListener: mListeners current size: " + N);
        }

        //解注册 zgw-2017/12/1 16:51
        @Override
        public void unregisterListener(IOnNewBookArrivedListener listener) throws RemoteException {
            /* 屏蔽CopyOnWriteArrayList，改用RemoteCallbackList @modify by zhuguowei 2017/12/4 15:09
            if (mListeners.contains(listener)) {
                mListeners.remove(listener);
            } else {
                Log.e(TAG, "unregisterListener: not found ,can not unregister !");
            }
            Log.e(TAG, "unregister listener：" + listener);
            Log.e(TAG, "registerListener: mListeners size = " + mListeners.size());
            屏蔽CopyOnWriteArrayList，改用RemoteCallbackList @modify by zhuguowei 2017/12/4 15:09 */
            //RemoteCallbackList zgw-2017/12/4 15:25
            boolean success = mListeners.unregister(listener);
            if (success) {
                Log.e(TAG, "unregisterListener: success");
            } else {
                Log.e(TAG, "unregisterListener: not fund,can not unregister");
            }
            final int N = mListeners.beginBroadcast();
            mListeners.finishBroadcast();
            Log.e(TAG, "unregisterListener: mListener current size: " + N);
        }
    };


    @Override
    public IBinder onBind(Intent intent) {
        int check = checkCallingOrSelfPermission("com.zhuguowei.chapter_2_4.ACCESS_BOOK_SERVICE");
        Log.e(TAG, "onBind: chenk = " + check);
//        if (check == PackageManager.PERMISSION_DENIED) {
//            Toast.makeText(this, "请申请权限！！！", Toast.LENGTH_SHORT).show();
//            return null;
//        }
//        Toast.makeText(this, "已获得权限！！！", Toast.LENGTH_SHORT).show();
        return mBinder;
    }

    @Override
    public void onDestroy() {
        //[] zgw-2017/12/1 16:51
        mIsServiceDestoryed.set(true);
        super.onDestroy();
    }

    //异步进行新书到达的通知工作 zgw-2017/12/1 16:56
    private class ServiceWorker implements Runnable {

        @Override
        public void run() {
            //判断服务是否销毁 zgw-2017/12/1 16:57
            while (!mIsServiceDestoryed.get()) {
                try {
                    //每5秒就增加一本新书，并通知所有感兴趣的用户 zgw-2017/12/1 16:58
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                int bookId = mBookList.size() + 1;
                Book newBook = new Book(bookId, "new book#" + bookId);
                try {
                    //回调监听 zgw-2017/12/1 17:03
                    onNewBookArrived(newBook);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //回调监听 zgw-2017/12/1 17:03
    private void onNewBookArrived(Book newBook) throws RemoteException {
        Log.e(TAG, "onNewBookArrived: newBook:" + newBook.toString());
        mBookList.add(newBook);
        /* 屏蔽CopyOnWriteArrayList，改用RemoteCallbackList @modify by zhuguowei 2017/12/4 15:09
        Log.e(TAG, "onNewBookArrived: mListeners size: " + mListeners.size() );
        for (int i = 0; i < mListeners.size(); i++) {
            IOnNewBookArrivedListener listener = mListeners.get(i);
            Log.e(TAG, "onNewBookArrived: notify listener: " + listener);
            listener.onNewBookArrived(newBook);
        }
        屏蔽CopyOnWriteArrayList，改用RemoteCallbackList @modify by zhuguowei 2017/12/4 15:09 */

        final int N = mListeners.beginBroadcast();
        for (int i = 0; i < N; i++) {
            IOnNewBookArrivedListener l = mListeners.getBroadcastItem(i);
            if (l != null) {
                //注意：客户端的方法onNewBookArrived如果是耗时的操作，需开启线程 zgw-2017/12/4 16:10
                l.onNewBookArrived(newBook);
            }
        }
        mListeners.finishBroadcast();
    }
}
